package com.yntx.usercenter.common.util;

import javax.crypto.KeyGenerator;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public class KeyGenerateUtil {

    /**
     * 将字节数组转换为十六进制字符串
     *
     * @param bytes 字节
     * @return {@link String}
     */
    public static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                sb.append("0");
            }
            sb.append(hex);
        }
        return sb.toString();
    }

    /**
     * 生成密钥
     *
     * @param algorithm 算法
     * @param keySize   关键尺寸
     * @return {@link String}
     * @throws NoSuchAlgorithmException 没有这样算法异常
     */
    public static String generateKey(String algorithm, int keySize) throws NoSuchAlgorithmException {
        //创建一个密钥生成器
        KeyGenerator keyGeneratorUtil = KeyGenerator.getInstance(algorithm);
        //初始化密钥长度
        keyGeneratorUtil.init(keySize, new SecureRandom());
        //生成一个密钥
        Key key = keyGeneratorUtil.generateKey();
        //获取密钥的字节数组
        byte[] keyBytes = key.getEncoded();
        //将字节数组转换为十六进制字符串
        String keyHex = bytesToHex(keyBytes);
        return keyHex;
    }

    /**
     * 生成密钥
     *
     * @param keySize 关键尺寸
     * @return {@link String}
     * @throws NoSuchAlgorithmException 没有这样算法异常
     */
    public static String generateKey(int keySize) throws NoSuchAlgorithmException {
        String defaultAlgorithm = "HmacSHA256";
        return generateKey(defaultAlgorithm, keySize);
    }

    /**
     * 生成密钥
     *
     * @return {@link String}
     * @throws NoSuchAlgorithmException 没有这样算法异常
     */
    public static String generateKey() throws NoSuchAlgorithmException {
        String defaultAlgorithm = "HmacSHA256";
        int defaultKeySize = 256;
        return generateKey(defaultAlgorithm, defaultKeySize);
    }

    public static void main(String[] args) throws NoSuchAlgorithmException {
        //指定算法和密钥长度
        String algorithm = "HmacSHA256";
        int keySize = 256;
        //生成accessKey
        String accessKey = generateKey(algorithm, keySize);
        System.out.println("accessKey: " + accessKey);
        //生成secretKey
        String secretKey = generateKey(algorithm, keySize);
        System.out.println("secretKey: " + secretKey);
    }
}
